package com.zjcode.cdcer.controller;

import com.alibaba.fastjson.JSONObject;
import com.chinatechstar.component.commons.consts.Consts;
import com.chinatechstar.component.commons.consts.Consts.CAS;
import com.chinatechstar.component.commons.controller.BaseController;
import com.chinatechstar.component.commons.supports.PageData;
import com.chinatechstar.component.commons.utils.SecurityUtil;
import com.zjcode.cdcer.model.basic.JsonObj;
import com.zjcode.cdcer.service.TkmSysUserService;
import com.zjcode.cdcer.utils.RedisUtils;
import io.swagger.annotations.ApiOperation;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
@RequestMapping("/v1/tkmSysUser/")
public class TkmSysUserController extends BaseController {

    @Autowired
    private TkmSysUserService tkmSysUserService;
    @Autowired
    private RedisUtils redisUtils;

    @Value("${studio.oauth-url}")
    private String oauthUrl;

    @PostMapping("updateUserPassword")
    @ApiOperation("修改密码")
    public JsonObj updateUserPassword(@RequestBody PageData pageData) {
        String id = String
            .valueOf(pageData.get("id"))
            .trim();
        if (!StringUtils.isNotEmpty(id)) {
            return JsonObj.error("用户id不能为空");
        }
        String password = String
            .valueOf(pageData.get("password"))
            .trim();
        if (!StringUtils.isNotEmpty(id)) {
            return JsonObj.error("用户所需修改的密码不能为空");
        }
        //TODO: 暂时不写逻辑
        int i = tkmSysUserService.updateUserPassword(id, password);
        if (i > 0) {
            return JsonObj.success("修改成功!");
        } else {
            return JsonObj.error("修改失败!");
        }

    }

    /**
     * 更新指定用户下的所extflag
     *
     * @param pageData
     * @return
     */
    @PostMapping("updateRecordExtflag")
    @ApiOperation("更新指定用户下的所extflag")
    public JsonObj updateRecordExtflag(@RequestBody PageData pageData) {
        Long userId = (Long) pageData.get("user");
        tkmSysUserService.updateRecordExtflag(String.valueOf(userId));
        return JsonObj.success("修改成功!");
    }

    /**
     * @param pageData
     * @return
     */
    @PostMapping("getToken")
    public JsonObj getToken(@RequestBody PageData pageData) {
        Map<String, Object> data = new HashMap<>();
        String sessionId = (String) pageData.get("sessionId");
        // 从redis中读取出sessionId中对应的数据
        String redisKey = CAS.URL_CAS_PREFIX + sessionId;
        String text = redisUtils.get(redisKey);
        JSONObject jobj = JSONObject.parseObject(text);
        // 将redisKey对应的数据从redis中移除
        redisUtils.del(redisKey);
        if (jobj != null) {
            String name = jobj.getString("name");
            String billNo = jobj.getString("billNo");

            try {
                billNo = SecurityUtil.decrypt(billNo);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

            // 模拟发送一次数据请求
            OkHttpClient client = new OkHttpClient();

            okhttp3.RequestBody requestBody = new FormBody.Builder()
                .add("scope", "ui")
                .add("grant_type", "password")
                .add("client_id", "browser")
                .add("username", name)
                .add("password", billNo)
                .add("tenantCode", "10001")
                .add("type", "account")
                .build();

            Request request = new Request.Builder()
                .addHeader("Authorization", "Basic YnJvd3Nlcjo=")
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                //.url("http://127.0.0.1:10003/api/uaa/oauth/token")
                .url(oauthUrl)
                .post(requestBody)
                .build();

            try {
                Response response = client
                    .newCall(request)
                    .execute();

                String resp = response
                    .body()
                    .string();
                JSONObject tokenObj = JSONObject.parseObject(resp);
                tokenObj
                    .entrySet()
                    .forEach(entry -> {
                        String key = entry.getKey();
                        Object value = entry.getValue();
                        data.put(key, value);
                    });

            } catch (IOException e) {
                throw new RuntimeException(e);
            }

            data.put("sessionId", sessionId);
            data.put("username", name);

            return JsonObj.success(data);
        } else {
            return JsonObj.error("session无效，请重新登录");
        }
    }
}
